from email.mime.text import MIMEText
from smtplib import SMTP_SSL
import os, sys, requests
from time import sleep
try:
    import lxml
    from bs4 import BeautifulSoup
except:
    os.system("pip3 install --user bs4 lxml")


def getTitle(a):
    try:
        return a["title"]
    except:
        return ""


def main():
    url = "http://202.118.47.14/"
    headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36 Edg/92.0.902.78' }
    try:
        html = requests.get(url, headers = headers)
    except:
        return
    soup = BeautifulSoup(html.content, 'lxml')
    v = list(map(getTitle, soup.findAll('a', { 'class': 'a2'})))
    print(v)

    with open("Log.yjs.cmu.edu.cn.txt", encoding="utf8", mode="w") as f:
        f.write('\n'.join(v))

    if os.path.exists("Log.2.yjs.cmu.edu.cn.txt"):
        with open("Log.yjs.cmu.edu.cn.txt", encoding="utf8", mode="r") as f:
            v2= f.read()
        with open("Log.2.yjs.cmu.edu.cn.txt", encoding="utf8", mode="r") as f:
            v3= f.read()
        os.system("cp Log.yjs.cmu.edu.cn.txt Log.2.yjs.cmu.edu.cn.txt")
        if v2!=v3:
            email_receiver='2907821379@qq.com'
            email_title='来自 研究生院 的消息'
            email_content= v2

            smtp_serv = 'smtp.qq.com'
            smtp_port = 465
            smtp_addr = '2907821379@qq.com'
            smtp_name = '2907821379'
            smtp_pass = ''

            smtp = SMTP_SSL(smtp_serv, smtp_port)
            smtp.set_debuglevel(0)
            smtp.ehlo(smtp_serv)
            smtp.login(smtp_name,smtp_pass)
            msg = MIMEText(email_content, 'plain', 'utf-8')
            msg["Subject"]=email_title
            msg["From"]=smtp_addr
            msg["To"]=email_receiver

            smtp.sendmail(smtp_addr, email_receiver, msg.as_string())

            smtp.close()
    else:
        os.system("cp Log.yjs.cmu.edu.cn.txt Log.2.yjs.cmu.edu.cn.txt")
        
while True:
    main()
    sleep(3600)